'use strict';

const Service = require('egg').Service;
const url = 'https://api.weixin.qq.com/cgi-bin';
const headers = { 'Content-Type': 'application/json' };
module.exports = class weChatService extends Service {

  async getToken() {
    const { appid, appSecret } = this.app.config.weChat;
    const api = `${url}/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
    const { data } = await this.ctx.curl(api, { dataType: 'json' });
    return data;
  }
  async getTemplate() {
    const { access_token } = await this.getToken();
    const api = `${url}/template/get_all_private_template?access_token=${access_token}`;
    const { data } = await this.ctx.curl(api, { dataType: 'json' });
    return data;
  }
  async orderCancellation({ openid, title = '', order = '', goods = '', refundAmount = '', remark = '' }) {
    const { access_token } = await this.getToken();
    const api = `${url}/message/template/send?access_token=${access_token}`;
    const { data } = await this.ctx.curl(api, {
      dataType: 'json',
      headers,
      type: 'post',
      data: {
        touser: openid,
        template_id: '_QFX20pNRvXV1T142o6iePwDKsieQ5R7r6YlNmSHXKs',
        url: 'http://weixin.qq.com/download',
        data: {
          first: {
            value: title,
            color: '#173177',
          },
          keyword1: {
            value: order,
            color: '#173177',
          },
          keyword2: {
            value: goods,
            color: '#173177',
          },
          keyword3: {
            value: refundAmount,
            color: '#173177',
          },
          remark: {
            value: remark,
            color: '#173177',
          },
        },
      },
    });
    return data;
  }

  async deliverGoods({ openid, title = '', logistics = '', goods = '', remark = '' }) {
    const { access_token } = await this.getToken();
    const api = `${url}/message/template/send?access_token=${access_token}`;
    const { data } = await this.ctx.curl(api, {
      dataType: 'json',
      headers,
      type: 'post',
      data: {
        touser: openid,
        template_id: '_QFX20pNRvXV1T142o6iePwDKsieQ5R7r6YlNmSHXKs',
        url: 'http://weixin.qq.com/download',
        data: {
          first: {
            value: title,
            color: '#173177',
          },
          keyword1: {
            value: logistics,
            color: '#173177',
          },
          keyword2: {
            value: goods,
            color: '#173177',
          },
          remark: {
            value: remark,
            color: '#173177',
          },
        },
      },
    });
    return data;
  }
};
